import { BaseScraper, type ScrapingResult } from './BaseScraper.js';
import { DataConverter, type TemplateData } from './DataConverter.js';
import type { CheerioAPI } from 'cheerio';

/**
 * Ant Design Pro 模板数据收集器
 */
export class AntDesignProScraper extends BaseScraper {
  private readonly githubApiUrl = 'https://api.github.com/repos/ant-design/ant-design-pro';
  private readonly proSiteUrl = 'https://pro.ant.design';
  
  // 模板分类映射
  private readonly templateCategories = new Map([
    ['dashboard', '仪表板'],
    ['form', '表单页'],
    ['list', '列表页'],
    ['profile', '详情页'],
    ['result', '结果页'],
    ['exception', '异常页'],
    ['account', '个人页'],
    ['editor', '编辑器'],
    ['analysis', '分析页'],
    ['monitor', '监控页'],
    ['workplace', '工作台'],
    ['basic-list', '基础列表'],
    ['table-list', '查询表格'],
    ['card-list', '卡片列表'],
    ['search', '搜索列表'],
    ['basic-form', '基础表单'],
    ['step-form', '分步表单'],
    ['advanced-form', '高级表单'],
    ['basic-profile', '基础详情页'],
    ['advanced-profile', '高级详情页'],
    ['success', '成功页'],
    ['fail', '失败页'],
    ['403', '403页'],
    ['404', '404页'],
    ['500', '500页'],
    ['center', '个人中心'],
    ['settings', '个人设置'],
  ]);

  constructor() {
    super('AntDesignProScraper', 'https://pro.ant.design');
  }

  /**
   * 执行数据抓取
   */
  async scrape(): Promise<ScrapingResult> {
    const startTime = Date.now();
    const result: ScrapingResult = {
      success: false,
      count: 0,
      data: [],
      errors: [],
      timestamp: new Date(),
      duration: 0,
    };

    try {
      this.log('🚀 开始抓取 Ant Design Pro 模板数据...');

      // 1. 从GitHub获取最新的模板信息
      this.emitProgress({
        stage: '获取GitHub仓库信息',
        current: 0,
        total: 100,
        message: '正在访问GitHub API...'
      });

      const repoInfo = await this.getRepositoryInfo();
      
      // 2. 获取官方示例页面模板
      this.emitProgress({
        stage: '获取官方示例',
        current: 25,
        total: 100,
        message: '正在访问Pro官网...'
      });

      const officialTemplates = await this.getOfficialTemplates();
      
      // 3. 获取GitHub中的页面模板
      this.emitProgress({
        stage: '获取GitHub模板',
        current: 50,
        total: 100,
        message: '正在分析GitHub源码...'
      });

      const githubTemplates = await this.getGithubTemplates();
      
      // 4. 合并所有模板
      const allTemplates = [...officialTemplates, ...githubTemplates];
      
      this.emitProgress({
        stage: '处理模板数据',
        current: 75,
        total: 100,
        message: `正在处理 ${allTemplates.length} 个模板...`
      });

      // 5. 处理和验证模板数据
      const processedTemplates: TemplateData[] = [];
      for (const template of allTemplates) {
        const validation = DataConverter.validateTemplate(template);
        if (validation.valid) {
          processedTemplates.push(template);
        } else {
          this.warn(`模板 ${template.name} 验证失败: ${validation.errors.join(', ')}`);
        }
      }

      result.data = processedTemplates;
      result.count = processedTemplates.length;
      result.success = true;
      
      this.log(`🎉 抓取完成! 成功收集 ${processedTemplates.length} 个Pro模板`);

    } catch (error) {
      const errorMsg = `抓取过程发生错误: ${error instanceof Error ? error.message : String(error)}`;
      result.errors.push(errorMsg);
      this.error(errorMsg);
    }

    result.duration = Date.now() - startTime;
    return result;
  }

  /**
   * 获取GitHub仓库信息
   */
  private async getRepositoryInfo(): Promise<any> {
    try {
      return await this.fetchJson(`${this.githubApiUrl}`);
    } catch (error) {
      this.warn('无法获取GitHub仓库信息，使用本地模板');
      return null;
    }
  }

  /**
   * 获取官方网站的模板
   */
  private async getOfficialTemplates(): Promise<TemplateData[]> {
    const templates: TemplateData[] = [];

    try {
      // 获取Pro官网的模板展示页面
      const html = await this.fetchPage('/docs/getting-started');
      const $ = this.parseHtml(html);

      // 创建一些基础的Pro模板
      templates.push(...this.createBuiltInTemplates());

    } catch (error) {
      this.warn('无法获取官方模板，使用内置模板');
      templates.push(...this.createBuiltInTemplates());
    }

    return templates;
  }

  /**
   * 获取GitHub中的模板文件
   */
  private async getGithubTemplates(): Promise<TemplateData[]> {
    const templates: TemplateData[] = [];

    try {
      // 获取src/pages目录结构
      const pagesContent = await this.fetchJson(`${this.githubApiUrl}/contents/src/pages`);
      
      if (Array.isArray(pagesContent)) {
        for (const item of pagesContent.slice(0, 10)) { // 限制数量
          if (item.type === 'dir' && this.templateCategories.has(item.name)) {
            const template = await this.createTemplateFromGithubDir(item);
            if (template) {
              templates.push(template);
            }
          }
        }
      }

    } catch (error) {
      this.warn(`获取GitHub模板失败: ${error instanceof Error ? error.message : String(error)}`);
    }

    return templates;
  }

  /**
   * 从GitHub目录创建模板
   */
  private async createTemplateFromGithubDir(dirInfo: any): Promise<TemplateData | null> {
    try {
      const categoryName = this.templateCategories.get(dirInfo.name) || dirInfo.name;
      
      // 尝试获取该目录下的主要文件
      const files = await this.fetchJson(dirInfo.url);
      let mainFile = null;
      
      if (Array.isArray(files)) {
        mainFile = files.find(f => f.name.includes('index.tsx') || f.name.includes('index.ts'));
      }

      let code = '';
      if (mainFile) {
        try {
          const fileContent = await this.fetchJson(mainFile.url);
          if (fileContent.content) {
            code = Buffer.from(fileContent.content, 'base64').toString('utf-8');
          }
        } catch {
          code = this.generateSampleCode(dirInfo.name, categoryName);
        }
      } else {
        code = this.generateSampleCode(dirInfo.name, categoryName);
      }

      return {
        name: dirInfo.name,
        title: `${categoryName}模板`,
        category: categoryName,
        description: `Ant Design Pro ${categoryName}页面模板，包含完整的页面布局和交互逻辑`,
        code: DataConverter.formatCode(code),
        framework: 'react',
        dependencies: ['antd', '@ant-design/pro-components', 'umi', 'react'],
        preview_url: `https://preview.pro.ant.design/${dirInfo.name}`,
        documentation_url: `https://pro.ant.design/docs/${dirInfo.name}`,
        tags: ['pro', 'template', categoryName.toLowerCase()],
        complexity: this.getComplexityLevel(dirInfo.name),
      };

    } catch (error) {
      this.error(`创建模板失败 ${dirInfo.name}: ${error instanceof Error ? error.message : String(error)}`);
      return null;
    }
  }

  /**
   * 创建内置模板
   */
  private createBuiltInTemplates(): TemplateData[] {
    const templates: TemplateData[] = [
      {
        name: 'dashboard-analysis',
        title: '分析页',
        category: '仪表板',
        description: '数据可视化分析页面，包含图表展示、数据统计等功能',
        code: this.generateAnalysisDashboard(),
        framework: 'react',
        dependencies: ['antd', '@ant-design/pro-components', '@ant-design/charts'],
        preview_url: 'https://preview.pro.ant.design/dashboard/analysis',
        documentation_url: 'https://pro.ant.design/docs/dashboard',
        tags: ['dashboard', 'analysis', 'charts'],
        complexity: 'advanced',
      },
      {
        name: 'form-basic',
        title: '基础表单',
        category: '表单页',
        description: '标准的数据录入表单，包含表单验证、提交等功能',
        code: this.generateBasicForm(),
        framework: 'react',
        dependencies: ['antd', '@ant-design/pro-form'],
        preview_url: 'https://preview.pro.ant.design/form/basic-form',
        documentation_url: 'https://pro.ant.design/docs/form',
        tags: ['form', 'basic', 'validation'],
        complexity: 'basic',
      },
      {
        name: 'table-list',
        title: '查询表格',
        category: '列表页',
        description: '标准的数据表格页面，包含查询、分页、操作等功能',
        code: this.generateTableList(),
        framework: 'react',
        dependencies: ['antd', '@ant-design/pro-table'],
        preview_url: 'https://preview.pro.ant.design/list/table-list',
        documentation_url: 'https://pro.ant.design/docs/list',
        tags: ['table', 'list', 'query'],
        complexity: 'intermediate',
      },
      {
        name: 'profile-basic',
        title: '基础详情页',
        category: '详情页',
        description: '标准的详情展示页面，适用于用户信息、订单详情等场景',
        code: this.generateBasicProfile(),
        framework: 'react',
        dependencies: ['antd', '@ant-design/pro-descriptions'],
        preview_url: 'https://preview.pro.ant.design/profile/basic',
        documentation_url: 'https://pro.ant.design/docs/profile',
        tags: ['profile', 'details', 'basic'],
        complexity: 'basic',
      },
      {
        name: 'result-success',
        title: '成功页',
        category: '结果页',
        description: '操作成功反馈页面，适用于提交成功、支付完成等场景',
        code: this.generateSuccessResult(),
        framework: 'react',
        dependencies: ['antd'],
        preview_url: 'https://preview.pro.ant.design/result/success',
        documentation_url: 'https://pro.ant.design/docs/result',
        tags: ['result', 'success', 'feedback'],
        complexity: 'basic',
      },
    ];

    return templates;
  }

  /**
   * 生成分析页Dashboard代码
   */
  private generateAnalysisDashboard(): string {
    return `import React from 'react';
import { Card, Col, Row, Statistic } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';

export default () => {
  return (
    <PageContainer
      header={{
        title: '数据分析',
        breadcrumb: {
          items: [
            { path: '', title: '首页' },
            { path: '', title: '仪表板' },
            { path: '', title: '分析页' },
          ],
        },
      }}
    >
      <Row gutter={16}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总销售额"
              value={112893}
              precision={2}
              valueStyle={{ color: '#3f8600' }}
              prefix={<ArrowUpOutlined />}
              suffix="元"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="访问量"
              value={8846}
              valueStyle={{ color: '#cf1322' }}
              prefix={<ArrowDownOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="支付笔数" value={6560} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="运营活动效果" value={78} suffix="%" />
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};`;
  }

  /**
   * 生成基础表单代码
   */
  private generateBasicForm(): string {
    return `import React from 'react';
import { Card, Form, Input, Button, Select, DatePicker, message } from 'antd';
import { PageContainer } from '@ant-design/pro-components';

const { Option } = Select;
const { TextArea } = Input;

export default () => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log('表单数据:', values);
    message.success('提交成功！');
  };

  return (
    <PageContainer
      header={{
        title: '基础表单',
        breadcrumb: {
          items: [
            { path: '', title: '首页' },
            { path: '', title: '表单页' },
            { path: '', title: '基础表单' },
          ],
        },
      }}
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            status: 'draft',
          }}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea rows={4} placeholder="请输入描述" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="draft">草稿</Option>
              <Option value="published">已发布</Option>
              <Option value="archived">已归档</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="publishDate"
            label="发布日期"
            rules={[{ required: true, message: '请选择发布日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={() => form.resetFields()}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};`;
  }

  /**
   * 生成表格列表代码
   */
  private generateTableList(): string {
    return `import React, { useState } from 'react';
import { ProTable, PageContainer } from '@ant-design/pro-components';
import { Button, Tag, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

export default () => {
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit">编辑</a>,
        <a key="delete">删除</a>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '查询表格',
        breadcrumb: {
          items: [
            { path: '', title: '首页' },
            { path: '', title: '列表页' },
            { path: '', title: '查询表格' },
          ],
        },
      }}
    >
      <ProTable
        columns={columns}
        request={async (params) => {
          // 模拟数据请求
          return {
            data: [
              {
                id: 1,
                name: '示例数据1',
                status: 'active',
                createdAt: new Date().toISOString(),
              },
              {
                id: 2,
                name: '示例数据2',
                status: 'inactive',
                createdAt: new Date().toISOString(),
              },
            ],
            total: 2,
            success: true,
          };
        }}
        rowKey="id"
        pagination={{
          defaultPageSize: 10,
        }}
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary">
            新建
          </Button>,
        ]}
      />
    </PageContainer>
  );
};`;
  }

  /**
   * 生成基础详情页代码
   */
  private generateBasicProfile(): string {
    return `import React from 'react';
import { Card, Descriptions, Avatar } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { UserOutlined } from '@ant-design/icons';

export default () => {
  return (
    <PageContainer
      header={{
        title: '基础详情页',
        breadcrumb: {
          items: [
            { path: '', title: '首页' },
            { path: '', title: '详情页' },
            { path: '', title: '基础详情页' },
          ],
        },
      }}
    >
      <Card>
        <Descriptions title="用户信息" bordered>
          <Descriptions.Item label="头像" span={3}>
            <Avatar size={64} icon={<UserOutlined />} />
          </Descriptions.Item>
          
          <Descriptions.Item label="用户名">张三</Descriptions.Item>
          <Descriptions.Item label="手机号">138****8888</Descriptions.Item>
          <Descriptions.Item label="邮箱">zhangsan@example.com</Descriptions.Item>
          
          <Descriptions.Item label="部门">技术部</Descriptions.Item>
          <Descriptions.Item label="职位">前端开发工程师</Descriptions.Item>
          <Descriptions.Item label="状态">
            <span style={{ color: 'green' }}>在职</span>
          </Descriptions.Item>
          
          <Descriptions.Item label="入职时间">2023-01-15</Descriptions.Item>
          <Descriptions.Item label="工作地点">北京</Descriptions.Item>
          <Descriptions.Item label="汇报对象">李经理</Descriptions.Item>
          
          <Descriptions.Item label="个人简介" span={3}>
            负责公司前端项目的开发和维护，熟悉React、Vue等主流前端框架，
            具有丰富的项目经验和团队协作能力。
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </PageContainer>
  );
};`;
  }

  /**
   * 生成成功页代码
   */
  private generateSuccessResult(): string {
    return `import React from 'react';
import { Result, Button } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { history } from 'umi';

export default () => {
  return (
    <PageContainer>
      <Result
        status="success"
        title="操作成功!"
        subTitle="您的请求已经成功提交，我们会在1-2个工作日内处理完成。"
        extra={[
          <Button type="primary" key="console" onClick={() => history.push('/')}>
            返回首页
          </Button>,
          <Button key="buy" onClick={() => history.goBack()}>
            返回上页
          </Button>,
        ]}
      />
    </PageContainer>
  );
};`;
  }

  /**
   * 生成示例代码
   */
  private generateSampleCode(name: string, category: string): string {
    return `import React from 'react';
import { PageContainer } from '@ant-design/pro-components';

export default () => {
  return (
    <PageContainer
      header={{
        title: '${category}',
        breadcrumb: {
          items: [
            { path: '', title: '首页' },
            { path: '', title: '${category}' },
          ],
        },
      }}
    >
      <div>
        <h2>${category}页面</h2>
        <p>这是一个基于Ant Design Pro的${category}模板页面。</p>
      </div>
    </PageContainer>
  );
};`;
  }

  /**
   * 获取复杂度级别
   */
  private getComplexityLevel(name: string): 'basic' | 'intermediate' | 'advanced' {
    const advanced = ['dashboard', 'analysis', 'monitor', 'editor'];
    const intermediate = ['form', 'table-list', 'search', 'step-form'];
    
    if (advanced.some(keyword => name.includes(keyword))) return 'advanced';
    if (intermediate.some(keyword => name.includes(keyword))) return 'intermediate';
    return 'basic';
  }
}